package com.ruoyi.energize.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.energize.domain.YancaoStoreDailySalesReport;
import com.ruoyi.energize.service.ICashOrderGoodsService;
import com.ruoyi.energize.service.IYancaoStoreDailySalesReportService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.energize.domain.CashOrder;
import com.ruoyi.energize.service.ICashOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * energizeController
 *
 * @author ruoyi
 * @date 2023-05-24
 */
@RestController
@RequestMapping("/energize/cashOrder")
public class CashOrderController extends BaseController
{
    @Autowired
    private ICashOrderService cashOrderService;
    @Autowired
    private ICashOrderGoodsService cashOrderGoodsService;
    @Autowired
    private IYancaoStoreDailySalesReportService yancaoStoreDailySalesReportService;

    /**
     * 查询energize列表
     */
    @PreAuthorize("@ss.hasPermi('energize:cashOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(CashOrder cashOrder)
    {
        startPage();
        List<CashOrder> list = cashOrderService.selectCashOrderList(cashOrder);
        return getDataTable(list);
    }
    /**
     *生成昨天的销售报表
     */
    @GetMapping("/makeYesterdayReport")
    public void makeYesterdayReport(){
        LocalDate localDate = LocalDate.now(); //获取今天的日期
        LocalDate yesterday = localDate.plusDays(-1); //前一天日期是今天减1
        LocalDateTime dateTimeMin = LocalDateTime.of(yesterday, LocalTime.MIN);
        LocalDateTime dateTimeMax = LocalDateTime.of(yesterday, LocalTime.MAX);
        List<YancaoStoreDailySalesReport> yancaoStoreDailySalesReportList=cashOrderService.selectCashOrderListByDate(dateTimeMin,dateTimeMax);
        if(!yancaoStoreDailySalesReportList.isEmpty() && yancaoStoreDailySalesReportList.size()>0){
            batchInsertStoreDailySalesReportService(yancaoStoreDailySalesReportList,dateTimeMin,dateTimeMax);
        }
    }
    /**
     * 通过门店列表 生成报表信息
     * 生成2023-03-13至2023-06-04日报表信息接口
     */
    @GetMapping("/makeReport")
    public void makeReport(){
        LocalDate startDate = LocalDate.of(2023, 04, 13);
        LocalDate endDate = LocalDate.of(2023, 06, 11);
        List<LocalDate> dates = this.getDatesBetween(startDate, endDate);
        for (LocalDate date : dates) {
            LocalDateTime dateTimeMax = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime dateTimeMin = LocalDateTime.of(date, LocalTime.MIN);
            List<YancaoStoreDailySalesReport> yancaoStoreDailySalesReportList=cashOrderService.selectCashOrderListByDate(dateTimeMin,dateTimeMax);
            if(!yancaoStoreDailySalesReportList.isEmpty() && yancaoStoreDailySalesReportList.size()>0){
                batchInsertStoreDailySalesReportService(yancaoStoreDailySalesReportList,dateTimeMin,dateTimeMax);
            }
        }
    }

    public static String  dateToWeek(Date date) throws ParseException {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1 < 0 ? 0 : cal.get(Calendar.DAY_OF_WEEK) - 1;
        String week= weekDays[w];
        return week;
    }

    public void batchInsertStoreDailySalesReportService(List<YancaoStoreDailySalesReport> yancaoStoreDailySalesReportList,LocalDateTime dateTimeMin,LocalDateTime dateTimeMax){
        if(!yancaoStoreDailySalesReportList.isEmpty() && yancaoStoreDailySalesReportList.size()>0){
            //查询出含烟草订单量/含烟草的销售额/含烟量占比/含烟草订单客单价/不含烟草客单价/纯烟草销售额/纯烟草占比
            //1.查询出某天/某个门店/包含烟草的统计数据
            List<YancaoStoreDailySalesReport> storeDailySalesReports=cashOrderGoodsService.selectCashOrderGoodsListByDate(dateTimeMin,dateTimeMax);
            for (YancaoStoreDailySalesReport yancaoStoreDailySalesReport:yancaoStoreDailySalesReportList){
                //数据中需要处理的数据
                try {
                    //将日期转化成星期
                    yancaoStoreDailySalesReport.setWeek(this.dateToWeek(yancaoStoreDailySalesReport.getDate()));
                    //客户单价
                    BigDecimal num2 = new BigDecimal(yancaoStoreDailySalesReport.getCustomerOrderAmount());
                    BigDecimal num1 = yancaoStoreDailySalesReport.getTotalSales();
                    BigDecimal result = num1.divide(num2, 3);
                    yancaoStoreDailySalesReport.setCustomerUnitPrice(result);
                    //记录是否匹配到烟草相关数据
                    Boolean includeCigaretteOrderLog=false;
                    //查询出某天/某个门店/包含烟草的统计数据进行数据处理
                    if(!storeDailySalesReports.isEmpty() && storeDailySalesReports.size()>0){
                        for (YancaoStoreDailySalesReport storeDailySalesReport:storeDailySalesReports){
                            if(yancaoStoreDailySalesReport.getStoreId().equals(storeDailySalesReport.getStoreId()) &&
                                    yancaoStoreDailySalesReport.getDate().equals(storeDailySalesReport.getDate())
                            ){
                                includeCigaretteOrderLog=true;
                                //纯烟草的销售额
                                yancaoStoreDailySalesReport.setCigaretteSales(storeDailySalesReport.getCigaretteSales());

                                //包含烟草的订单总数
                                yancaoStoreDailySalesReport.setIncludeCigaretteOrderAmount(storeDailySalesReport.getIncludeCigaretteOrderAmount());
                                //不包含烟草的订单总数
                                yancaoStoreDailySalesReport.setNotIncludeCigaretteOrderAmount(yancaoStoreDailySalesReport.getCustomerOrderAmount()-yancaoStoreDailySalesReport.getIncludeCigaretteOrderAmount());
                                //统计下包含烟草数量的总销售额
                                String oidString=storeDailySalesReport.getStoreName();//为了将GROUP_CONCAT后的值通过一个变量返回，所以赋值到storeName字段上
                                BigDecimal realTotalPrice=cashOrderService.selectCashOrderByOidStr(oidString);
                                //包含烟草的销售额
                                yancaoStoreDailySalesReport.setIncludeCigaretteOrderSales(realTotalPrice);
                                //包含烟草的客单价
                                BigDecimal num3 = new BigDecimal(yancaoStoreDailySalesReport.getIncludeCigaretteOrderAmount());
                                BigDecimal num4 = yancaoStoreDailySalesReport.getIncludeCigaretteOrderSales();
                                BigDecimal result1 = num4.divide(num3, 3);
                                yancaoStoreDailySalesReport.setIncludeCigaretteUnitPrice(result1);

                                //不包含烟草的销售额
                                yancaoStoreDailySalesReport.setNotIncludeCigaretteOrderSales(yancaoStoreDailySalesReport.getTotalSales().subtract(yancaoStoreDailySalesReport.getIncludeCigaretteOrderSales()));
                                //不包含烟草的客单价
                                BigDecimal num5 = new BigDecimal(yancaoStoreDailySalesReport.getNotIncludeCigaretteOrderAmount());
                                BigDecimal num6 = yancaoStoreDailySalesReport.getNotIncludeCigaretteOrderSales();
                                BigDecimal result2;
                                if(num5.equals(BigDecimal.ZERO)){
                                    result2= BigDecimal.valueOf(0);
                                }else{
                                    result2 = num6.divide(num5, 3);
                                }

                                yancaoStoreDailySalesReport.setNotIncludeCigaretteUnitPrice(result2);

                                //含烟销售额占比
                                BigDecimal result3=num4.divide(num1,2);
                                yancaoStoreDailySalesReport.setIncludeCigaretteRatio(result3);
                                //纯烟销售额占比
                                BigDecimal num7=storeDailySalesReport.getCigaretteSales();
                                BigDecimal result4=num7.divide(num1,2);
                                yancaoStoreDailySalesReport.setCigaretteRatio(result4);
                            }
                        }
                    }
                    //说明未包含烟草相关订单
                    if(includeCigaretteOrderLog.equals(false)){
                        //纯烟草的销售额
                        yancaoStoreDailySalesReport.setCigaretteSales(BigDecimal.valueOf(0));
                        //包含烟草的订单总数
                        yancaoStoreDailySalesReport.setIncludeCigaretteOrderAmount(0);
                        //不包含烟草的订单总数
                        yancaoStoreDailySalesReport.setNotIncludeCigaretteOrderAmount(yancaoStoreDailySalesReport.getCustomerOrderAmount());
                        //包含烟草的销售额
                        yancaoStoreDailySalesReport.setIncludeCigaretteOrderSales(BigDecimal.valueOf(0));
                        //包含烟草的客单价
                        yancaoStoreDailySalesReport.setIncludeCigaretteUnitPrice(BigDecimal.valueOf(0));
                        //不包含烟草的销售额
                        yancaoStoreDailySalesReport.setNotIncludeCigaretteOrderSales(yancaoStoreDailySalesReport.getTotalSales());
                        //不包含烟草的客单价
                        yancaoStoreDailySalesReport.setNotIncludeCigaretteUnitPrice(result);
                        //含烟销售额占比
                        yancaoStoreDailySalesReport.setIncludeCigaretteRatio(BigDecimal.valueOf(0));
                        //纯烟销售额占比
                        yancaoStoreDailySalesReport.setCigaretteRatio(BigDecimal.valueOf(0));
                    }
                    //将数据插入到对应的表中
                    int i=yancaoStoreDailySalesReportService.insertYancaoStoreDailySalesReport(yancaoStoreDailySalesReport);
                    System.out.println("插入了"+i+"条门店日销售报表数据:"+yancaoStoreDailySalesReport.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 获取两个日期之间的所有日期
     * @param startDate
     * @param endDate
     * @return
     */
    public static List<LocalDate> getDatesBetween(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> dates = new ArrayList<>();
        long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
        for (int i = 0; i <= numOfDaysBetween; i++) {
            LocalDate date = startDate.plusDays(i);
            dates.add(date);
        }
        return dates;
    }

    /**
     * 导出energize列表
     */
    @PreAuthorize("@ss.hasPermi('energize:cashOrder:export')")
    @Log(title = "energize", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CashOrder cashOrder)
    {
        List<CashOrder> list = cashOrderService.selectCashOrderList(cashOrder);
        ExcelUtil<CashOrder> util = new ExcelUtil<CashOrder>(CashOrder.class);
        util.exportExcel(response, list, "energize数据");
    }

    /**
     * 获取energize详细信息
     */
    @PreAuthorize("@ss.hasPermi('energize:cashOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(cashOrderService.selectCashOrderById(id));
    }

    /**
     * 新增energize
     */
    @PreAuthorize("@ss.hasPermi('energize:cashOrder:add')")
    @Log(title = "energize", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CashOrder cashOrder)
    {
        return toAjax(cashOrderService.insertCashOrder(cashOrder));
    }

    /**
     * 修改energize
     */
    @PreAuthorize("@ss.hasPermi('energize:cashOrder:edit')")
    @Log(title = "energize", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CashOrder cashOrder)
    {
        return toAjax(cashOrderService.updateCashOrder(cashOrder));
    }

    /**
     * 删除energize
     */
    @PreAuthorize("@ss.hasPermi('energize:cashOrder:remove')")
    @Log(title = "energize", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(cashOrderService.deleteCashOrderByIds(ids));
    }
}
